#include "role.h"
#include<QTimer>
#include<QGraphicsScene>
#include <QDebug>

role::role(QPixmap pixmap, QObject *parent):
    QObject(parent), QGraphicsPixmapItem(pixmap)
{
    rundir=0;
    runpos=0;
    setPos(50,270);
    isJump = false;

    //设置定时器，形成跑动效果
    QTimer* runtimer=new QTimer(this);
    connect(runtimer,&QTimer::timeout,this,[=](){run();});
    runtimer->start(100);
    rise = new QPropertyAnimation(this, "pos");
    fall = new QPropertyAnimation(this, "pos");
    x = 50;
    y = 270;
    this->setPixmap(this->pixmap().scaledToHeight(100));
}

void role::run()
{
    QPixmap pixmap;
    if(runpos==0)
    {
        pixmap = QPixmap(":/res/role2.png");
        runpos=1;
        rundir=0;
    }
    else if(runpos==1)
    {
        if(rundir==0)
        {
            pixmap = QPixmap(":/res/role1.png");
            runpos=2;
        }
        else
        {
            pixmap = QPixmap(":/res/role3.png");
            runpos=0;
        }
    }
    else if(runpos==2)
    {
        pixmap = QPixmap(":/res/role2.png");
        runpos=1;
        rundir=1;
    }
    this->setPixmap(pixmap.scaledToHeight(100));
}


void role::jump(){

    //跳跃动画
    rise->setStartValue(this->pos());
    rise->setEndValue(this->pos()+QPoint(0,-70));
    rise->setEasingCurve(QEasingCurve::OutQuad);
    rise->setDuration(450);
    rise->start();

    connect(rise, &QPropertyAnimation::finished, [=](){
        fall->setStartValue(this->pos());
        fall->setEndValue(this->pos()+QPoint(0,+70));
        fall->setEasingCurve(QEasingCurve::InQuad);
        fall->setDuration(450);
        fall->start();});
    //跳跃动画结束后继续奔跑
    connect(fall,&QPropertyAnimation::finished,[=]{
        isJump = false;});
}

void role::rolestart(){

}

void role::setPos1(const QPointF &pos)
{
    m_pos = pos;
    this->setPos(m_pos);
    // y = m_pos.y();
}


void role::KeyPressEvent(QKeyEvent *k){
    if(k->key()==Qt::Key_Up){


        if(y > 70)
        {
            fall->setStartValue(QPointF(x,y));
            fall->setEndValue(QPointF(x,y - 100));
            fall->setEasingCurve(QEasingCurve::InQuad);
            fall->setDuration(250);
            fall->start();
            y -= 100;
        }
    }
    if(k->key()==Qt::Key_Down){
        if(y < 300)
        {
            fall->setStartValue(QPointF(x,y));
            fall->setEndValue(QPointF(x,y + 100));
            fall->setDuration(250);
            fall->start();
            y += 100;
        }
    }
    if(k->key()==Qt::Key_Space && !isJump){
        isJump = true;
        jump();

    }
}

